//
//  addNewFriend.m
//  HappyStore
//
//  Created by 陈锋 on 16/7/18.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "addNewFriend.h"
#import "addressCell.h"
#import "addNewFriendDetailVC.h"

static NSString *CellIdentifier = @"Cell";
@interface addNewFriend (){

    NSInteger page;
    NSMutableArray * dataArr;

}

@end

@implementation addNewFriend

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    self.tabBarController.tabBar.hidden = YES;
    
    page = 1;
    [self sendRequest];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    
    self.title = @"好友邀请";
    
    // 注册
    UINib * nib = [UINib nibWithNibName:@"addressCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
    
    dataArr = [NSMutableArray array];
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    
    self.tableView.mj_footer = footer;
}

-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
 [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:dataArr.count];
    return dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    addressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    NSDictionary * dict = dataArr[indexPath.row];
    
    [cell.imageview sd_setImageWithURL:[NSURL URLWithString:dict[@"headPhoto"]]];
    cell.name.text = dict[@"userName"];
    
    NSDictionary * jsonDict = [LSHttpTool dictionaryWithJsonString:dict[@"reason"]];
    
    if ([jsonDict[@"reason"] isEqualToString:@""] || [jsonDict[@"reason"] isEqualToString:@"null"]) {
        
        cell.phone.text = @"请求添加为好友";
        
    }else{
    
        cell.phone.text = jsonDict[@"reason"];
    
    }
    
    cell.phone.textColor = [UIColor lightGrayColor];
    
    cell.imageview.layer.masksToBounds = YES;
    cell.imageview.layer.cornerRadius = 5.0f;
    
    cell.addBtn.layer.masksToBounds = YES;
    cell.addBtn.layer.cornerRadius = 5.0f;
    cell.addBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    
    cell.addBtn.tag = indexPath.row;
    
    if ([dict[@"isAudit"] isEqualToString:@"0"]) {
        
        [cell.addBtn setTitle:@"接受" forState:0];
        [cell.addBtn setTitleColor:[UIColor whiteColor] forState:0];
        [cell.addBtn setBackgroundColor:[UIColor colorWithRed:0.0/255.0f green:180.0/255.0f blue:222.0/255.0f alpha:1.0f]];
        [cell.addBtn addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
        
    }else if ([dict[@"isAudit"] isEqualToString:@"1"]){
    
        [cell.addBtn setTitle:@"已添加" forState:0];
        [cell.addBtn setTitleColor:[UIColor lightGrayColor] forState:0];
        [cell.addBtn setBackgroundColor:[UIColor whiteColor]];
        cell.addBtn.userInteractionEnabled = NO;
    
    }else if ([dict[@"isAudit"] isEqualToString:@"2"]){
        
        [cell.addBtn setTitle:@"已拒绝" forState:0];
        [cell.addBtn setTitleColor:[UIColor lightGrayColor] forState:0];
        [cell.addBtn setBackgroundColor:[UIColor whiteColor]];
        cell.addBtn.userInteractionEnabled = NO;
        
    }
    
    if ([dict[@"addType"] isEqualToString:@"申请方"] && [dict[@"isAudit"] isEqualToString:@"0"]) {
        
        cell.addBtn.userInteractionEnabled = NO;
        [cell.addBtn setTitle:@"申请中" forState:0];
        [cell.addBtn setBackgroundColor:[UIColor lightGrayColor]];
        [cell.addBtn setTitleColor:[UIColor whiteColor] forState:0];
        
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 0;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    addNewFriendDetailVC * addNewFriendDetail = [[addNewFriendDetailVC alloc]init];
    NSDictionary * dict = dataArr[indexPath.row];
    addNewFriendDetail.userId = dict[@"userId"];
    addNewFriendDetail.userType = dict[@"userType"];
    addNewFriendDetail.btnType = dict[@"isAudit"];
    addNewFriendDetail.addType = dict[@"addType"];
    
    [self.navigationController pushViewController:addNewFriendDetail animated:YES];
}

#pragma mark - 接受
-(void)add:(UIButton *)button{
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    
    NSDictionary * dict = dataArr[button.tag];

    if ([button.titleLabel.text isEqualToString:@"接受"]) {
        NSMutableDictionary * dictData = [NSMutableDictionary dictionary];
        // 请求数据
        
        [dictData setValue:@(page) forKey:@"page"];
        [dictData setValue:allConstMemberid forKey:@"userId"];
        [dictData setValue:allConstMemberToken forKey:@"token"];
        [dictData setValue:dict[@"userId"] forKey:@"targetuserId"];
        [dictData setValue:@(1) forKey:@"type"];
        
        NSString *str = @"Add_Delete_Friend_app_social.im.lensum?";
        
        [LSHttpTool sendHttpData:str params:dictData success:^(id responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];

            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                if (page == 1) {

                    [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
                    
                }
                
                [self.tableView.mj_footer endRefreshing];
                
            }else{
                
                [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
                [self.tableView.mj_footer endRefreshing];
            }
            
            page = 1;
            [self sendRequest];
            
        } failure:^(NSError *error) {

            [self showSingleIconBubble:@"网络连接错误"];
            
        }];
    }

}

-(void)loadMoreData{

    page++;
    [self sendRequest];

}

#pragma mark - 网络请求
-(void)sendRequest{
    
    NSMutableDictionary * dictData = [NSMutableDictionary dictionary];
    // 请求数据

    [dictData setValue:@(page) forKey:@"page"];
    [dictData setValue:allConstMemberid forKey:@"userId"];
    [dictData setValue:allConstMemberToken forKey:@"token"];
    
    
    NSString *str = @"getAddFriendList_app_social.im.lensum?";
    
    [LSHttpTool sendHttpData:str params:dictData success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            if (page == 1) {
                
                dataArr = nil;
                dataArr = dicInfo[@"data"];
                
                
            }else{
                
                NSArray *arr = dicInfo[@"data"];;
                NSMutableArray * mtArr = [NSMutableArray array];
                for (NSDictionary * dict in dataArr) {
                    [mtArr addObject:dict];
                }
                for (NSDictionary * dict in arr) {
                    [mtArr addObject:dict];
                }
                dataArr = nil;
                dataArr = mtArr;
                
            }
            
            [self.tableView.mj_footer endRefreshing];
            
        }else{
            
            self.tableView.rowHeight = screenH;
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        [self hideBubble];
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        
    }];

}

@end
